// 主程序入口
document.addEventListener('DOMContentLoaded', () => {
    const table = document.getElementById('myTable');

    // 渲染初始数据
    tableData.renderToTable(initTableData, table);
    
    contextMenu.init();

    // 右键菜单事件
    table.addEventListener('contextmenu', (e) => {
        e.preventDefault();
        if (e.target.tagName === 'TD' && tableSelection.selectedCells.length > 0) {
            contextMenu.show(e.pageX, e.pageY);
        } else {
            contextMenu.hide();
        }
    });

    // 点击其他地方隐藏菜单
    document.addEventListener('click', (e) => {
        if (!contextMenu.menu.contains(e.target)) {
            contextMenu.hide();
        }
    });

    // 选择相关事件
    table.addEventListener('mousedown', (e) => {
        if (e.button === 0 && e.target.tagName === 'TD') {
            tableSelection.isSelecting = true;
            tableSelection.clearSelection();
            const cell = e.target;
            tableSelection.selectedCells.push(cell);
            cell.classList.add('selected');
        }
    });

    table.addEventListener('mouseover', (e) => {
        tableSelection.handleMouseOver(e, table);
    });

    document.addEventListener('mouseup', (e) => {
        if (e.button === 0) {
            tableSelection.isSelecting = false;
        }
    });

    // 撤销快捷键
    document.addEventListener('keydown', (e) => {
        if (e.ctrlKey && e.key === 'z') {
            e.preventDefault();
            if (tableState.undo(table)) {
                tableSelection.clearSelection();
                contextMenu.hide();
            }
        }
    });
}); 